<?php
/**
 *
* Copyright(c) 201x,
* All rights reserved.
*
* 功 能：日志格式化
* @author cabing_2005@126.com
* @date 2014-8-13
* 版 本：1.0
 */

abstract class LogFormat{
    public  static function  format($params)
    {
    }
    /**
     * 获取时间
     */
    public static function getTime()
    {
        if(isset($_SERVER["REQUEST_TIME"])){
            return $_SERVER["REQUEST_TIME"];
        }
        return time();
    }

    /**
     * 获取ip
     */
    public static function getIp()
    {
        $clientIp = '0.0.0.0';
        if (isset($_SERVER['CLIENT_IP']))
        {
            $clientIp = $_SERVER['CLIENT_IP'];
        }
        elseif (isset($_SERVER['X_FORWARDED_FOR']))
        {
            $clientIp = $_SERVER['X_FORWARDED_FOR'];
        }
        elseif (isset($_SERVER['REMOTE_ADDR']))
        {
            $clientIp = $_SERVER['REMOTE_ADDR'];
        }

        return $clientIp;
    }
}

class MysqlLogFormatException extends Exception{}
/**
 * mysql format
 */
class MysqlLogFormat extends LogFormat{

    /**
     * 拼接插入的sql语句
     */
    public static function format($params)
    {
        if(!is_array($params)) {
            throw new MysqlLogFormatException("params not right in ".__LINE__);
        }
        $sql_portion = "(";
        $params["create_time"] = self::getTime();
        $params["ip"] = self::getIp();
        //todo 优化
        $keys = array_keys($params);
        foreach($keys as $key){
            $sql_portion .= mysql_real_escape_string($key).",";
        }
        $sql_portion = substr($sql_portion,0,-1);
        $sql_portion .= ")values(";
        $values = array_values($params);
        foreach($values as $value){
            $sql_portion .= "'".mysql_real_escape_string($value)."',";
        }
        $sql_portion = substr($sql_portion,0,-1);
        $sql_portion .= ")";
        return $sql_portion;
    }
}


class FileLogFormatException extends Exception{}
/**
 *
 * file format
 */
class FileLogFormat extends LogFormat{

    /**
     *
     * @param array $params
     * @return array
     *
     */
    public static function format($params)
    {
        if(!isset($params[LOG_SPLIT]) || !is_array($params)){
            throw new FileLogFormatException("params not right in ".__LINE__);
        }

        $ret_arr = array();
        $separator = $params[LOG_SPLIT];
        $path = LOG_BASE_PATH.DIRECTORY_SEPARATOR.date("Y-m-d")
                .DIRECTORY_SEPARATOR.$params["project"];
        if(!is_dir($path)) {
            if(mkdir($path,0700,true)){
                throw new FileLogFormatException("mkdir faild ".__LINE__);
            }
        }
        $file = $path.DIRECTORY_SEPARATOR.$params["module"].LOG_BASE_EXT;
        unset($params[LOG_SPLIT],$params["project"],$params["module"]);

        $ret_arr["file"] = $file;
        $params["create_time"] = self::getTime();
        $params["ip"] = self::getIp();
        $ret_arr["content"] = implode($separator,$params);

        return $ret_arr;
    }
}





